package com.epoint.springsecuritylearning.exception;

import com.alibaba.fastjson.annotation.JSONField;
import com.epoint.springsecuritylearning.user.domain.SysUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 将用户需要登入的用户封装到这个对象里，会被 security框架调用
 */
@Data
@NoArgsConstructor
public class LoginUserDetails implements UserDetails {

    private SysUser user;

    private Set<String> permissions;

    // 不需要序列化（在存入redis的时候）
    @JSONField(serialize = false)
    private List<GrantedAuthority> permissions_Temp;

    public LoginUserDetails(SysUser user, Set<String> permissions){
        this.user = user;
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 为了防止每次调用的时候 都要走一遍
        if(permissions_Temp == null){
            permissions_Temp = permissions.stream().map((permission) -> {
                return new SimpleGrantedAuthority(permission);
            }).collect(Collectors.toList());
        }
        return permissions_Temp;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
